<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    //产品列表
    public function lists(){
    	$where[] = ['menu_article_id','=','2'];
    	$articles = Db::table('article')->where($where)->orderBy('order','DESC')->paginate(15);

    	foreach ($articles as $key => $value) {
            if(!empty($value->image)){
                $value->image = Storage::url($value->image);
            }
        }

    	return view('product_lists',['articles'=>$articles]);
    }

    //添加产品
    public function add_product(Request $request){

    	return view('product_add');
    }

    //添加新闻动作
    public function add_product_do(Request $request){
    	$input = $request->input();
    	$input['time'] = time();
    	$input['menu_article_id'] = '2';

    	$image = !empty($request->file('image'))?$request->file('image'):[];

        if(!empty($image)){
            $path = $image->store('public/upload');
            $input['image'] = $path;
        }else{
            $path = null;
            unset($input['image']);
        }

    	if(empty($input['id'])){
    		Db::table('article')->insert($input);
    	}else{
    		Db::table('article')->where('id','=',$input['id'])->update($input);
    	}

    	return response()->json([
            'status' => 1,
            'result' => [],
            'message' => '操作成功！'
        ]);
    }

    //编辑新闻
    public function edit_product(Request $request,$id){
    	$where[] = ['id','=',$id];
    	$articles = Db::table('article')->where($where)->first();
    	$articles->image = Storage::url($articles->image);

    	return view('product_edit',['articles'=>$articles,'id'=>$id]);
    }
}
